package com.fand.common.controller;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;

@Controller
public class ErrorPageController {
	private final static Log log = LogFactory.getLog(HomeController.class);

	@RequestMapping(value = { "/error/404.htm" })
	public String error404(final Exception ex, final Model model) {
		this.setModel(ex, model);

		return "error/404";
	}

	@RequestMapping(value = { "/error/500.htm" })
	public String error500(final Exception ex, final Model model) {
		this.setModel(ex, model);

		return "error/500";
	}

	@ExceptionHandler(Exception.class)
	public @ResponseBody
	Map<String, Object> runtimeExceptionHandler(final RuntimeException runtimeException) {
		ErrorPageController.log.error(runtimeException.getLocalizedMessage());

		final Map<String, Object> model = Maps.newTreeMap();

		model.put("status", false);

		return model;
	}

	private void setModel(final Exception ex, final Model model) {
		model.addAttribute("message", ex.getMessage());

		if (ex != null) {
			ex.printStackTrace();
		}

		if (ErrorPageController.log.isErrorEnabled()) {
			ErrorPageController.log.error(ex.getMessage(), ex);
		}
	}
}
